<?php

namespace backend\widgets;


use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Json;

class BatchColumn extends Widget
{
    public $label;

    public $name;

    public $actions = [];

    public $options = [];

    public $submitOptions = [];

    public $confirm;

    /**
     * @var BatchView
     */
    public $batch;

    public function run()
    {
        if (empty($this->actions)) {
            return;
        }

        if (!isset($this->options['class'])) {
            $this->options['class'] = 'form-control';
        }

        if (!isset($this->submitOptions['class'])) {
            $this->submitOptions['class'] = 'btn btn-primary';
        }

        $this->submitOptions['disabled'] = true;
        $this->submitOptions['value'] = $this->label;

        $doName = 'do' . ucfirst($this->name);

        if (isset($this->batch->model)) {
            echo Html::activeDropDownList($this->batch->model, $this->name, $this->actions, $this->options);
            echo "\n";
            echo Html::activeInput('submit', $this->batch->model, $doName, $this->submitOptions);
        } else {
            echo Html::dropDownList($this->name, null, $this->actions, $this->options);
            echo "\n";
            echo Html::input('submit', $doName,  $this->label, $this->submitOptions);
        }

        $this->registerClientScript();
    }

    public function registerClientScript()
    {
        if (!$this->confirm || !is_array($this->confirm)) {
            return;
        }

        $options = Json::encode($this->confirm);

        $id = $this->batch->options['id'];
        if (isset($this->batch->model)) {
            $name = Html::getInputName($this->batch->model, $this->name);
        } else {
            $name = $this->name;
        }

        $this->batch->getView()->registerJs("jQuery('#$id').ycmfBatchView('setConfirmColumn', '{$name}', $options);");
    }
} 